<template>
  <el-tabs v-model="activeName" class="demo-tabs">
    <el-tab-pane label="性能用例" name="first">
      <div class="table_header">
        <el-button type="success" @click="upload_file_dialog = !upload_file_dialog">创建</el-button>
        <el-button type="warning" @click="dialogVisible = true">删除</el-button>
        <el-button>数据聚合</el-button>
        <el-input v-model="search" :suffix-icon="Search" class="table_search" placeholder="搜索关键字"/>
      </div>

      <el-table
          :data="TasktableData"
          stripe
          border
          max-height="700"
          style="width: 100%"
      >
        <el-table-column prop="id" label="ID" fixed width="180" sortable/>
        <el-table-column prop="name" label="任务名" fixed width="180" sortable/>
        <el-table-column prop="owner" fixed label="创建人" width="90" sortable/>
        <el-table-column prop="ctime" fixed label="创建时间" width="120" sortable/>
        <el-table-column fixed="right" label="操作" width="200">
          <template #default="scope">
            <el-button type="success" link>
              <el-icon>
                <VideoPlay/>
              </el-icon>
            </el-button>
            <el-button type="warning" link>
              <el-icon>
                <View/>
              </el-icon>
            </el-button>
            <el-button type="danger" link>
              <el-icon>
                <Delete/>
              </el-icon>
            </el-button>
            <el-button type="primary">数据导出</el-button>
          </template>
        </el-table-column>
      </el-table>
      <Pagination @change="ListFio" v-model:page="page"/>


    </el-tab-pane>
    <el-tab-pane label="性能数据" name="task">
      <div v-if="oper" class="operation">
        <el-checkbox-group v-model="checkList" v-for="item in OperList"
                           style="display:inline-block; padding-left: 20px">
          <el-checkbox :label="item"/>
        </el-checkbox-group>

        <el-select v-model="feild_value" placeholder="Select">
          <el-option
              v-for="item in Field"
              :key="item"
              :label="item"
              :value="item"
          />
        </el-select>
        <el-button type="success" @click="SortData" style="width: 80px">按字段排序</el-button>
        <el-button type="success" style="width: 80px">查看数据</el-button>
      </div>
      <div id="datas">

      </div>
      <div class="table_header">
        <el-button type="success" @click="upload_file_dialog = !upload_file_dialog">数据录入</el-button>
        <el-button type="danger" @click="ExportFio">下载</el-button>
        <el-button type="warning" @click="dialogVisible = true">删除</el-button>
        <template v-if="multipleSelection.length > 1">
          <el-divider direction="vertical"/>
          <template v-if="oper">
            <el-button type="warning" @click="DataAny">
              <el-icon>
                <Refresh/>
              </el-icon>
            </el-button>
          </template>
          <template v-else>
            <el-button type="warning" @click="DataAny">
              <el-icon>
                <TrendCharts/>
              </el-icon>
            </el-button>
          </template>
        </template>
        <el-input v-model="searchtext" :suffix-icon="Search" class="table_search" placeholder="搜索关键字"/>
      </div>
      <el-table
          :data="filterTableData"
          stripe
          border
          max-height="700"
          style="width: 100%"
          @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" fixed width="55"/>
        <el-table-column prop="job_name" label="任务名" fixed width="180" sortable/>
        <el-table-column prop="bs" fixed label="bs" width="80" sortable/>
        <el-table-column prop="size" fixed label="size" width="80" sortable/>
        <el-table-column prop="filesize" fixed label="filesize" width="80" sortable/>
        <el-table-column prop="numjobs" label="并发" width="80" sortable/>
        <el-table-column prop="iodepth" label="iodepth" width="80"/>

        <el-table-column prop="wbw" label="写带宽(MiB)"/>
        <el-table-column prop="wiops" label="写IOPS"/>
        <el-table-column prop="wlazy" label="写平均时延(ms)"/>
        <el-table-column prop="rbw" label="读带宽(MiB)"/>
        <el-table-column prop="riops" label="读IOPS"/>
        <el-table-column prop="rlazy" label="读平均时延(ms)"/>
        <el-table-column prop="client" label="客户端"/>
        <el-table-column prop="client" label="分析结论"/>
        <el-table-column fixed="right" label="操作" width="150">
          <template #default="scope">
            <el-button type="primary" link @click="EditFioData(scope.row)">编辑</el-button>
            <el-button type="info" link @click="taskdetail=!taskdetail">详情</el-button>
            <el-button type="danger" link>删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <Pagination @change="ListFio" v-model:page="page"/>
    </el-tab-pane>

    <el-tab-pane label="测试分析" name="test">
      <el-select placeholder="选择待执行的任务">
        <el-option key="item" label="item" value="item"/>
      </el-select>

      <el-button>网络检查</el-button>
      <el-button>磁盘单盘压力测试</el-button>
      <el-button>环境信息获取</el-button>
      <el-button>帮助文档</el-button>
    </el-tab-pane>
  </el-tabs>
  <el-dialog v-model="upload_file_dialog" title="性能数据录入" width="25%" :before-close="handleClose">
    <el-upload
        ref="uploadRef"
        class="upload-demo"
        action="#"
        limit="1"
        accept=".xlsx"
        method="post"
        :auto-upload="false"
    >
      <template #trigger>
        <el-button type="primary">选择文件</el-button>
      </template>

      <el-button class="ml-3" type="success" @click="submitUpload">
        上传
      </el-button>

      <template #tip>
        <div class="el-upload__tip">
          xlsx files
        </div>
      </template>
    </el-upload>
  </el-dialog>
  <el-drawer
      ref="drawerRef"
      v-model="editdrower"
      title="fio测试数据"
      :before-close="handleClose"
      direction="rtl"
      class="demo-drawer">
    <el-form>
      <el-form-item label="任务名">
        <el-input clearable v-model="cur_fio_data.job_name"></el-input>
      </el-form-item>

      <el-form-item label="客户端数量">
        <el-input clearable v-model="cur_fio_data.client_num"></el-input>
      </el-form-item>

      <el-form-item label="分析结论" class="top-item">
        <el-input
            v-model="cur_fio_data.desc"
            :autosize="{ minRows: 6, maxRows: 24}"
            label-position="top"
            type="textarea"
            placeholder="请输入JSON格式的字符串"
        />
      </el-form-item>
    </el-form>
    <el-button type="success" @click="SubmitModify" style="float: right;margin-right: 20px">保存</el-button>
  </el-drawer>

</template>

<script lang="ts" setup>
import * as echarts from 'echarts';
import {Hide, Search, View} from '@element-plus/icons-vue'
import type {UploadInstance} from 'element-plus'
import {ElMessage} from 'element-plus'
import {onMounted, reactive, ref, watch,computed} from 'vue'
import {fio} from "./fio"
import {performance} from "./performance"
import Pagination from "@/components/common/Pagination.vue";

const activeName = ref('task')
const upload_file_dialog = ref(false)
var searchtext = ref('')
var search = ref('')
var taskdetail = ref(false)
var editdrower = ref(false)
var feild_value = ref('numjobs')
var oper = ref(false)
const action = ref("http://localhost:8080/api/v1/fio/file_upload")

const uploadRef = ref<UploadInstance>()

var OperList = ["读IOPS", "读带宽", "写IOPS", "写带宽"]
var OperDict = {
  "读IOPS": "riops",
  "读带宽": "rbw",
  "写带宽": "wbw",
  "写IOPS": "wiops",
}
var Field = ["numjobs","job_name", "bs", "size"]
const checkList = ref(['读IOPS', "读带宽", "写IOPS", "写带宽"])

const handleClose = () => {
  editdrower.value = false
  upload_file_dialog.value = false
}

const ExportFio = async () => {
  var res = await fio.Export()

}


var cur_fio_data = {}
const EditFioData = (row) => {
  cur_fio_data = row
  editdrower.value = true
}
const SubmitModify = () =>{

}

const value: boolean = true


let page = reactive({"page": 1, "size": 15, "total": 0})
const tableData = ref([])

const multipleSelection = ref([])

const dialogVisible = ref(false)
const handleSelectionChange = (val) => {
  multipleSelection.value = val
}

const TasktableData = []

onMounted(() => {
  ListFio()
  ListPerformance()
})

const ListFio = async () => {
  var res = await fio.List(page)
  tableData.value = res.data
  page.total = res.total
}

const ListPerformance = async () => {
  var res = await performance.List(page)
  TasktableData.value = res.data
  page.total = res.total
}
const submitUpload = () => {
  uploadRef.value!.submit()
}

const filterTableData = computed(() =>
    tableData.value.filter(
        (data) =>
            !searchtext.value ||
            data.job_name.toLowerCase().includes(searchtext.value.toLowerCase())
    )
)
const DataAny = async () => {
  // if (multipleSelection.value.length > 20) {
  //   ElMessage.warning("最后支持20项数据对此，当前：" + multipleSelection.value.length);
  //   return
  // }
  for (var i in checkList.value) {
    DataChart(checkList.value[i], "datas")
  }
}

const GetEl = async (otype, idattr) => {
  var chartDom = document.getElementById(otype);
  if (chartDom == null) {
    var datas = document.getElementById(idattr);
    chartDom = document.createElement("div");
    chartDom.setAttribute("id", otype)
    chartDom.style.height = "400px"
    chartDom.style.width = "100%"
    datas.appendChild(chartDom)
  }
}

const DelEl = async (otype) => {
  otype = OperDict[otype]
  var div = document.getElementById(otype);
  if (div != null) {
    div.remove()
  }
}

// 随机生成颜色
const handleColors = () => {
  let color = ''
  let r = Math.floor(Math.random() * (120) + 79)
  let g = Math.floor(Math.random() * (120) + 79)
  let b = Math.floor(Math.random() * (120) + 79)
  color = `rgb(${r},${g},${b})`
  return color// 所有方法的拼接都可以用ES6新特性`其他字符串{$变量名}`替换
}
var colorList = []

const DataChart = async (otype, idattr) => {
  multipleSelection.value = sortFun(multipleSelection.value, feild_value.value, "desc")
  if (otype == undefined) {
    return
  }
  var left_label = otype

  var right_label = ""
  otype = OperDict[otype]
  if (otype == undefined) {
    return
  }
  oper.value = true
  if (multipleSelection.value.length == 0) {
    ElMessage({
      type: 'error',
      message: "请选择元素",
      showClose: true,
    })
    return
  }
  await GetEl(otype, idattr)
  var chartDom = document.getElementById(otype);
  var x = []
  var y = []
  var lazy = []
  var lazy_type = ""
  if (otype.includes("r")) {
    lazy_type = "rlazy"
    right_label = "R_lazy"
  } else {
    lazy_type = "wlazy"
    right_label = "W_lazy"
  }
  multipleSelection.value.forEach((item, index) => {
    if (feild_value.value.length != 0) {
      x.push(item[feild_value.value])
    } else {
      x.push(item.job_name)
    }

    y.push(item[otype])
    lazy.push(item[lazy_type])
  })
  if (colorList.length < lazy.length) {
    for (var i = 0; i <= (lazy.length - colorList.length); i++) {
      var color = handleColors()
      colorList.push(color)
    }
  }
  var myChart = echarts.init(chartDom);
  var option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
      }
    },
    toolbox: {
      feature: {
        dataView: {show: true, readOnly: false},
        magicType: {show: true, type: ['line', 'bar']},
        restore: {show: true},
        saveAsImage: {show: true}
      }
    },
    legend: {
      data: ['Evaporation', 'Precipitation', 'Temperature']
    },
    grid: {
      left: "6%",
      containLabel: true
    },
    xAxis: [
      {
        type: 'category',
        data: x,
        axisPointer: {
          type: 'shadow'
        },
        axisLabel: {
          rotate: 45,
        },
      }
    ],
    yAxis: [ {
      type: 'value',
      name: "时延",
      position:"right",
      axisLabel: {
        width: '120', // 将内容的宽度固定
        overflow: 'truncate', // 超出的部分截断
        truncate: '...', // 截断的部分用...代替
      },
    },
      {
        type: 'value',
        name: left_label,
        position:"left",
        axisLabel: {
          width: '120', // 将内容的宽度固定
          overflow: 'truncate', // 超出的部分截断
          truncate: '...', // 截断的部分用...代替
        }

      },],
    series: [
      {
        type: 'line',
        name: right_label,
        inverse: true,
        tooltip: {
          valueFormatter: function (value) {
            return value;
          }
        },
        data: lazy
      },
      {
        type: 'bar',
        name: left_label,
        inverse: true,
        yAxisIndex: 1,
        tooltip: {
          valueFormatter: function (value) {
            return value;
          }
        },
        itemStyle: {
          normal: {
            color: function (params) {
              return colorList[params.dataIndex % colorList.length];
            },
            label: {
              show: false, //开启显示
              textStyle: {
                //数值样式
                color: 'black',
                fontSize: 12,
              },
            }
          },

        },
        data: y
      },
    ]
  };
  myChart.setOption(option);
}

function getArrDifference(arr1, arr2) {
  return arr1.concat(arr2).filter(function (v, i, arr) {
    return arr.indexOf(v) === arr.lastIndexOf(v);
  });
}

watch(checkList, (newValue, oldValue) => {
  var arr3 = getArrDifference(newValue, oldValue)
  for (var i in arr3) {
    if (oldValue.some(item => item == arr3[i])) {
      DelEl(arr3[i])
    } else {
      DataChart(arr3[i], "datas")
    }
  }
})

const sortFun = (arr, name, type) => {
  const compare = (prop) => {
    return function (obj1, obj2) {
      let val1 = obj1[prop];
      let val2 = obj2[prop];
      if (val1 < val2) {
        return -1;
      } else if (val1 > val2) {
        return 1;
      } else {
        return 0;
      }
    }
  }

  if (type == 'desc') {
    return arr.sort(compare(name));
  } else {
    return arr.sort(compare(name)).reverse();
  }
}

const SortData = () => {
  for (var i in checkList.value) {
    DataChart(checkList.value[i], "datas")
  }

}

</script>

<style scoped lang="scss">
@import "@/styles/table_header.scss";

.el-table .warning-row {
  --el-table-tr-bg-color: var(--el-color-warning-light-9);
}

.el-table .success-row {
  --el-table-tr-bg-color: var(--el-color-success-light-9);
}

.operator {
  padding-top: 8px;
}

.el-input {
  float: right;
  width: 200px;
}

.el-pagination {
  float: right;
}

.operation .el-button {
  border: 0;
  padding: 0;
  margin: 0;
  width: 50px
}

#datas {
  padding-left: 0;
  width: 100%;
  height: 100%;
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  grid-auto-rows: minmax(100px, auto);
  grid-auto-flow: dense;
}

.el-select {
  width: 100px;
  margin-left: 40px;
}
</style>
